package com.yoshino.leetcode.improve40.tenth;

import java.util.HashMap;
import java.util.Map;

class LRUCache {

    class DLinkNode {
        int key;
        int value;
        DLinkNode pre;
        DLinkNode next;
        public DLinkNode(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public DLinkNode() {
        }
    }

    private Map<Integer, DLinkNode> map;
    private int size;
    private int capacity;
    private DLinkNode head, tail;
    public LRUCache(int capacity) {
        map = new HashMap<>();
        head = new DLinkNode();
        tail = new DLinkNode();
        head.next = tail;
        tail.pre = head;
        this.size = 0;
        this.capacity = capacity;
    }
    
    public int get(int key) {
        DLinkNode node = map.get(key);
        if (node == null) {
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkNode node = map.get(key);
        if (node != null) {
            node.value = value;
            moveToHead(node);
            return;
        }
        node = new DLinkNode(key, value);
        map.put(key, node);
        addToHead(node);
        size++;
        if (size > capacity) {
            DLinkNode tail = removeTail();
            map.remove(tail.key);
            size--;
        }
    }

    private DLinkNode removeTail() {
        DLinkNode pre = tail.pre;
        pre.pre.next = tail;
        tail.pre = pre.pre;
        return pre;
    }

    private void moveToHead(DLinkNode node) {
        removeNode(node);
        addToHead(node);
    }

    private void removeNode(DLinkNode node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    private void addToHead(DLinkNode node) {
        node.next = head.next;
        head.next = node;
        node.next.pre = node;
        node.pre = head;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */